<?php

namespace Controllers;

class MembersController extends ControllerAbstract {
    
    public function registrationActionGet() {
        
        if ($this->isMemberLoggedIn()) {
            $this->redirect('/');
        }
        
        $this->renderView();
    }  
    
    public function registrationActionPost() {
        
        if ($this->isMemberLoggedIn()) {
            $this->redirect('/');
        }
        
        $registrationForm = $this->_di->getRegistrationForm();
        
        $registrationValues = $this->post(
            [
                'login'    => FILTER_SANITIZE_STRING,
                'email'    => FILTER_SANITIZE_STRING,
                'password' => FILTER_SANITIZE_STRING
            ]
        );
        
        if ($registrationForm->isValid($registrationValues)) {
            $membershipModel = $this->_di->getMembershipModel();
            $memberId = $membershipModel->add($registrationValues);
            
            $this->sessionStorage()->store(
                'member', 
                [
                    'id'    => $memberId,
                    'login' => $registrationValues['login']
                ]
            );
            
            $this->redirect('/');
        }
        
        $this->renderView(
            [
                'errors' => $registrationForm->getErrors(),
                'form'   => $registrationValues
            ]
        );
    } 
    
    public function loginActionGet() {
        
        if ($this->isMemberLoggedIn()) {
            $this->redirect('/');
        }
        
        $this->renderView();
    }
    
    public function loginActionPost() {
        
        if ($this->isMemberLoggedIn()) {
            $this->redirect('/');
        }
        
        $loginValues = $this->post(
            [
                'login'    => FILTER_SANITIZE_STRING, 
                'password' => FILTER_SANITIZE_STRING
            ]
        );
        
        $membershipModel = $this->_di->getMembershipModel();
        if ($membershipModel->login($loginValues['login'], $loginValues['password'])) {
            $this->sessionStorage()->store('member', $membershipModel->getCurrentMember()); 
        
            $this->redirect('/');
        }
        
        $this->renderView(
            [
                'error' => 'Login or password incorrect',
                'form'  => $loginValues,
            ]
        );
    }
    
    public function logoutActionGet() {
        $this->sessionStorage()->endSession();
        
        $this->redirect('/members/login');
    }
}

